package com.ll.blog.controller;

import com.ll.blog.common.ApiResponse;
import com.ll.blog.contant.ExceptionEnum;
import com.ll.blog.entity.Tag;
import com.ll.blog.service.ITagService;
import io.swagger.models.auth.In;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;

/**
 *标签管理
 * @author 作者
 * @since 2024-03-02
 */
@Validated
@RestController
public class TagController {
    @Resource
    ITagService tagService;

    /**
     * 添加标签接口
     * @param name 标签名
     * @return
     */
    @PostMapping("/tag")
    public ApiResponse add(String name){
        Tag tag = new Tag();
        tag.setName(name);
        boolean saved = tagService.save(tag);
        if (!saved){
            return ApiResponse.error(ExceptionEnum.SAVE_ERROR);
        }
        return  ApiResponse.success("添加成功");
    }

    /**
     * 删除单个标签接口
     * @param id 标签id
     * @return
     */
    @DeleteMapping("/admin/tag/{id}")
    public ApiResponse del(@PathVariable Integer id){
        boolean b = tagService.removeById(id);
        if (!b){
            return ApiResponse.error(ExceptionEnum.DELETE_ERROR);
        }
        return  ApiResponse.success("删除成功");
    }
    /**
     * 删除多个标签接口
     * @param list 标签id数组
     * @return
     */
    @Transactional
    @DeleteMapping("/admin/tag")
    public ApiResponse del(@RequestBody List<Integer> list){
        boolean b = tagService.removeBatchByIds(list);
        if(!b){
            throw new RuntimeException();
        }
        return  ApiResponse.success("删除成功");
    }

    /**
     * 更新标签接口
     * @param id 标签id
     * @param name 标签名
     * @return
     */
    @PutMapping("/admin/tag")
    public ApiResponse update(@PathVariable Integer id,@NotEmpty(message = "请传递标签名") String name){
        Tag tag = new Tag();
        tag.setId(id);
        tag.setName(name);
        boolean b = tagService.updateById(tag);
        if (!b){
            return ApiResponse.error(ExceptionEnum.UPDATE_ERROR);
        }
        return ApiResponse.success("更改成功");
    }

    /**
     * 获取所有标签
     */

    @GetMapping("/tag/all")
    public ApiResponse findAll(){
        List<Tag> list = tagService.list();
        return ApiResponse.success(list);
    }

}
